﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace OnTheWay.Tool
{
    public class S3DES
    {
        private SymmetricAlgorithm _CSP;

        /// <summary>
        /// 创建3DES算法，注意：如果不是md5作为秘钥，key、iv值需要有8位
        /// </summary>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <param name="ismd5"></param>
        public S3DES(string key, string iv,bool ismd5 = true)
        {
            _CSP = new DESCryptoServiceProvider();

            byte[] bytekey = Convert.FromBase64String(key);
            int index = 0;
            if (ismd5)
            {
                byte[] keys = new byte[8];
                index = 0;
                for (int i = 0; i < 8; i++)
                {
                    keys[i] = bytekey[index];
                    index += 2;
                }
                _CSP.Key = keys;
            }
            else
            {
                _CSP.Key = bytekey;
            }

            byte[] byteiv = Convert.FromBase64String(iv);
            if (ismd5)
            {
                byte[] ivs = new byte[8];
                index = 0;
                for (int i = 0; i < 8; i++)
                {
                    ivs[i] = byteiv[index];
                    index += 2;
                }
                _CSP.IV = ivs;
            }
            else
            {
                _CSP.IV = byteiv;
            }
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        public string EncryptString(string Value)
        {
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            ct = _CSP.CreateEncryptor(_CSP.Key, _CSP.IV);
            byt = Encoding.UTF8.GetBytes(Value);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        public string DecryptString(string Value)
        {
            ICryptoTransform ct;
            MemoryStream ms;
            CryptoStream cs;
            byte[] byt;
            ct = _CSP.CreateDecryptor(_CSP.Key, _CSP.IV);
            byt = Convert.FromBase64String(Value);
            ms = new MemoryStream();
            cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            cs.Close();
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}
